import { sendSuccess, sendFail } from "./utils";
import {
  getList,
  getAll,
  addData,
  updateData,
  deleteData,
} from "./utils/readFile";

export default [
  {
    url: "/api/system/role/list",
    timeout: 1000,
    method: "get",
    response: (ctx) => {
      const list = getList("role", ctx.query);
      const res = {
        list,
        total: list.length,
      };
      return sendSuccess(res);
    },
  },
  {
    url: "/api/system/role",
    timeout: 1000,
    method: "post",
    response: (ctx) => {
      const { roleName, roleKey } = ctx.body;
      const data = getAll("role");
      let flag = data.some((item) => item.roleName === roleName);
      if (flag) {
        return sendFail(null, "角色已存在");
      }
      flag = data.some((item) => item.roleKey === roleKey);
      if (flag) {
        return sendFail(null, "权限字符已存在");
      }
      const res = addData("role", ctx.body);
      return sendSuccess(res.id);
    },
  },
  {
    url: "/api/system/role",
    timeout: 1000,
    method: "put",
    response: (ctx) => {
      const { id, roleName, roleKey } = ctx.body;
      const data = getAll("role");
      let flag = data.some(
        (item) => item.id != id && item.roleName === roleName
      );
      if (flag) {
        sendFail(null, "角色已存在");
      }
      flag = data.some((item) => item.roleKey === roleKey);
      if (flag) {
        sendFail(null, "权限字符已存在");
      }
      updateData("role", ctx.body);
      return sendSuccess();
    },
  },
  {
    url: "/api/system/role",
    timeout: 1000,
    method: "delete",
    response: (ctx) => {
      const { id } = ctx.query;
      const flag = deleteData("role", id);
      if (!flag) {
        return sendFail(null, "角色不存在");
      }
      return sendSuccess();
    },
  },
];
